<?php

/*
 * Armory
 * mer.shanghai@gmail.com
 */
class Armory {

  var $config = array();

  function __construct($config=array()) {
    $this->config['lang']      = 'zh_cn';
    $this->config['host']      = 'http://cn.wowarmory.com/';    
    $this->config['item']      = 'item-tooltip.xml';
    $this->config['armory']    = 'character-sheet.xml';
    $this->setconfig($config);
  }

  function __destruct() {

  }

  function setconfig($config=array()) {
    if (!empty($config) && is_array($config)){
      foreach($config as $key=>$value) {
        $this->config[$key] = $value;
      }
    }
  }

  function get($key) {
    return $this->config[$key];
  }
  
  function getsetting($lang, $ff='') {
    return stream_context_create(array(
      'http'=>array(
        'method'  => "GET",
        'timeout' => 10,
        'header'  => "Accept-language: $lang\r\n" . 
        ($ff ? 'User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2) Gecko/20100115 Firefox/3.6\r\n' : '')
      )
    ));
  }
  
  
  function get_item($itemid) {
    $itemid = (int)$itemid;
    if(!$itemid) return 'error: itemid';
    $setting = $this->getsetting(substr($this->config['lang'],3,2));
    if($content = file_get_contents($this->config['host'].$this->config['item']."?i=$itemid", false, $setting)) {
      preg_match("/<div class=\"myTable\">(.+?)<\/td>/ies",$content,$return);
      $return = $return[1];
      if($return) {
       $return = preg_replace("/<img class=\"(.*?)\" src=\".+\/([^\/]+)\.png\">/","<span class=\"socketImg \\2\"></span>",$return);
       return $return;
      }
    }
    else {
      return 'timeout';
    }
  }
  
  function get_armory($realm, $name) {
    $realm = urlencode(trim($realm));
    $name  = urlencode(ucfirst(strtolower(trim($name))));
    $setting = $this->getsetting(substr($this->config['lang'],3,2), true);
    if($realm && $name) {
      if($content = file_get_contents($this->config['host'].$this->config['armory']."?r=$realm&cn=$name", false, $setting)) {        
        return arr_dump($this->parsexml($content));
      }
      else {
        return array();
      }
    }
    else {
      return array();
    }
  }
  
  function get_boss() {
    
  }
  
  function get_instance() {
    
  }
  
  
  //From : Itemstatlite by T.G.
  function parsexml($str) {
		$xml = simplexml_load_string($str);
		
		if(!$xml instanceof SimpleXMLElement){
			return array();
		}

		$t = $xml->xpath('/page/characterInfo');
		if(!isset($t[0])){
			return array();
		};
		
		$t = $xml->xpath('/page/characterInfo/@errCode');
		if(isset($t[0]) && $t[0]['errCode']){
			return array();
		};

		$rt = array();
		
		//character 		
		$t = $xml->xpath('/page/characterInfo/character');
		foreach($t[0]->attributes() as $i => $v){
			$i = strtoupper($i);
			$rt[$i] = (string)$v;
		}
		
		$rt['TALENTURL'] = $this->config['host']."character-talents.xml?" . $rt['CHARURL'];
		$rt['CHARURL']   = $this->config['host']."character-sheet.xml?" . $rt['CHARURL'];
		$rt['GUILDURL']  = $this->config['host']."guild-info.xml?" . $rt['GUILDURL'];
		
		$rt['ICON'] = $this->config['host']."_images/portraits/wow/{$rt['GENDERID']}-{$rt['RACEID']}-{$rt['CLASSID']}.gif";
		
		//arenaTeam
		$t = $xml->xpath('/page/characterInfo/character/arenaTeams/arenaTeam');
		foreach($t as $team){			
			$n = 'ARENATEAM_' . (string)$team['size'] . '_';
			$rt[$n . 'NAME'] = (string)$team['name'];
			$rt[$n . 'RANK'] = (string)$team['rating'];
			$rt[$n . 'URL'] = $this->config['host']."team-info.xml?" . (string)$team['teamUrl'];
		}
		
		//talent
		$t = $xml->xpath('/page/characterInfo/characterTab/talentSpecs/talentSpec[@active=1]');
		$t = $t[0];
		$rt ['TALENT'] = "{$t['prim']}[{$t['treeOne']}/{$t['treeTwo']}/{$t['treeThree']}]";
		
		//pvp
		$t = $xml->xpath('/page/characterInfo/characterTab/pvp/lifetimehonorablekills');		
		$rt['LIFETIMEHONORABLEKILLS'] = (string)$t[0]['value'];
		
		//professions
		$t = $xml->xpath('/page/characterInfo/characterTab/professions/skill');
		$rt['PROFESSIONS'] = '';
		foreach($t as $profess){
			$rt['PROFESSIONS'] .= "{$profess['name']}[{$profess['value']}/{$profess['max']}] ";
		}
		$rt['PROFESSIONS'] = trim($rt['PROFESSIONS']);

		//health & mana
		$t = $xml->xpath('/page/characterInfo/characterTab/characterBars');
		$t = $t[0];
		$rt['HEALTH'] = (string)$t->health['effective'];
		$rt['MANA'] = (string)$t->secondBar['effective'];
		
		//baseStats resistances defenses
		$t = $xml->xpath('/page/characterInfo/characterTab/baseStats');
		$t = $t[0];
		foreach($t as $i => $v){
			$i = strtoupper($i);
			$rt[$i] = $this->lazy_val($v);
		}
		
		$t = $xml->xpath('/page/characterInfo/characterTab/resistances');
		$t = $t[0];
		foreach($t as $i => $v){
			$i = strtoupper($i);
			$rt[$i] = $this->lazy_val($v);
		}
				
		$t = $xml->xpath('/page/characterInfo/characterTab/defenses');
		$t = $t[0];
		foreach($t as $i => $v){
			$i = strtoupper($i);
			$rt[$i] = $this->lazy_val($v);
		}
		
		//melee
		$t = $xml->xpath('/page/characterInfo/characterTab/melee');
		$t = $t[0];
		foreach($t as $i => $v){
			$i = strtoupper($i);
			if(in_array($i,array("POWER","HITRATING","CRITCHANCE","EXPERTISE"))){
				$rt["MELEE_$i"] = $this->lazy_val($v);
			}
		}
		$rt["MELEE_HASTE"] = $t->mainHandSpeed['hastePercent'].'%';
		
		//range
		$t = $xml->xpath('/page/characterInfo/characterTab/ranged');
		$t = $t[0];
		foreach($t as $i => $v){
			$i = strtoupper($i);
			if(in_array($i,array("POWER","HITRATING","CRITCHANCE"))){
				$rt["RANGED_$i"] = $this->lazy_val($v);
			}
		}
		
		//spell
		$t = $xml->xpath('/page/characterInfo/characterTab/spell');
		$t = $t[0];
		$rt['SPELL_HEAL'] = $this->lazy_val($t->bonusHealing);
		$rt['SPELL_HITRATING'] = $this->lazy_val($t->hitRating);
		$rt['SPELL_PENETRATION'] = $this->lazy_val($t->penetration);
		$rt['SPELL_MANAREGEN'] = (string)$t->manaRegen['notCasting'];
		$rt['SPELL_HASTE'] = $t->hasteRating['hastePercent'] . '%';
		$t = $xml->xpath('/page/characterInfo/characterTab/spell/bonusDamage/*/@value[not (/page/characterInfo/characterTab/spell/bonusDamage/*/@value >.)]');
		$rt['SPELL_POWER'] = (string)$t[0]['value'];
		$t = $xml->xpath('/page/characterInfo/characterTab/spell/critChance/*/@percent[not (/page/characterInfo/characterTab/spell/critChance/*/@percent >.)]');
		$rt['SPELL_CRITCHANCE'] = $t[0]['percent'].'%';
		
		//items
		$rt['ITEMSLOTS'] = '';
		$t = $xml->xpath('/page/characterInfo/characterTab/items');
		$t = $t[0];
		foreach($t as $item) {
			$slot = $item['slot'];
			$item_id = $item['id'];
			$icon = $item['icon'];
			$icon = $this->config['host']."wow-icons/_images/21x21/{$icon}.png";
			$rt['ITEMSLOTS'] .= $rt["ITEMSLOT_$slot"] = "<a class=\"tip\" rel=\"item,{$item_id}\"><img src=\"$icon\"></a>";
		}
		
		//all done
		return $rt;
	}

  private static function lazy_val($o) {
		foreach(array('effective','percent','value') as $i){
			if(isset($o[$i])){
				return $o[$i] . ($i =='percent' ? '%' : '');
			}
		}
		return '';
	}
  
}


?>